package com.ruiyian.netty.nettyclient;

import com.ruiyian.netty.nettyclientTask.NettyStarterTask;
import com.ruiyian.system.domain.ServerEq;
import com.ruiyian.system.service.ServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author chong
 * @email 673426164@qq.com
 * @create 2021/3/12
 * Desc: 客户端启动连接plc服务
 *   初始化连接plc
 */
@Slf4j
@Component
public class NettyConfig {
    @Autowired
    private ServerService serverService;
    @Value("${initStart.ifLinkPlc}")
    private Boolean ifLinkPlc;
    @Value("${initStart.taskServer}")
    private Boolean taskServer;

    /**
     * 初始化连接
     * 查询数据库表中所有ip和port不为空的设备
     * netty客户端尝试连接并保存至connectMap内存中
     * 连接plc服务器,连接多个服务器循环 开启
     */
    @PostConstruct
    public void initClient() {
        try {
            if(ifLinkPlc){
                List<ServerEq> servers = serverService.selectList(new ServerEq("1"));
                log.info("plc运行----->"+servers.size());
                if(servers.size()>0){
                    for(ServerEq item: servers){
                        NettyStarter.clientStart(item.getHost(), item.getPort());
                    }
                }
            }
            // 不太知道这个是干嘛的,2023.12.06先杆掉
//            if(taskServer){
//                List<ServerEq> serverEqs = serverService.selectTaskServer();
//                log.info("plc定时----->"+serverEqs.size());
//                if(serverEqs.size()>0){
//                    for(ServerEq item: serverEqs){
//                        NettyStarterTask.clientStart(item.getHost(), item.getPort());
//                    }
//                }
//            }
        } catch (Exception e) {
            log.error("plc连接异常",e.getMessage());
        }
    }

}
